from django_filters import rest_framework as filters
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import  ModelViewSet
from books.models import BookInfo, HeroInfo
from books.serializers import BookInfoModelSerializers, HeroInfoModelSerializers


class MyPageNum(PageNumberPagination):
    # 约定：/books/?page=1&pagesize=5
    # 通过类属性，定义查询字符串参数
    page_query_param = 'page' # 指定查询字符串参数key为'page'，传递取第几页
    page_size_query_param = 'pagesize' # 指定查询字符串参数key为'pagesize'，传递每页数目
    page_size = 5 # 指定后端默认按照每页几个划分
    max_page_size = 10 # 每页数目的最大值

    def get_paginated_response(self, data):
        return Response(data={
            'code': 0,
            'errmsg': 'ok',
            'lists': data
        })

class BookFilter(filters.FilterSet):
    bread__gt = filters.NumberFilter(field_name='bread', lookup_expr='gt')
    bread__lt = filters.NumberFilter(field_name='bread', lookup_expr='lt')
    class Meta:
        model = BookInfo
        fields = ["bread__gt", "bread__lt"]

class BookView(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializers

    throttle_scope = "books"

    ordering_fields = ['bread', 'bcomment', 'bpub_date']

    # 指定使用django-filter后端
    filter_backends = [filters.DjangoFilterBackend,]
    # 指定自定义的过滤器
    filterset_class = BookFilter


    pagination_class = MyPageNum
    # 自定义的身份认证
    authentication_classes = [SessionAuthentication]
    @action(methods=['get'],detail=False, url_path="latest")
    def latest(self, request, *args, **kwargs):
        user = request.user
        book = self.queryset.latest('bpub_date')
        serializers = self.get_serializer(instance=book)
        return Response(data=serializers.data)





class HerosView(ModelViewSet):
    queryset = HeroInfo.objects.all()
    serializer_class = HeroInfoModelSerializers
    throttle_scope = "heros"
    # 自定义的身份认证
    authentication_classes = [SessionAuthentication]
